<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title">
					<el-select v-model="selectValue" size="mini" placeholder="请选择" class="select" @change="selectChange">
							<el-option
								v-for="item in selectOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
				</view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<button class="uni-button upload" type="primary" size="mini" @click="tempFile">导入模板下载</button>
				<button class="uni-button upload" type="primary" size="mini" @click="uploadFile">批量导入</button>
				<input class="uni-search" type="text" v-model="query" placeholder="请输入学号/工号/姓名" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" @click="delTable">批量删除</button>
			</view>
		</view>
		<view class="uni-container">
			<uni-clientdb ref="udb" :collection="collectionName" :options="options" :where="where" field="username,nickname,role,college{college_id,college_name},mobile,email,status,register_date"
			 page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
			 v-slot:default="{data,pagination,loading,error}">
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection"
				 @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">学号/工号</uni-th>
						<uni-th align="center">姓名</uni-th>
						<uni-th align="center">角色</uni-th>
						<uni-th align="center">学院</uni-th>
						<uni-th align="center">手机号</uni-th>
						<uni-th align="center">用户状态</uni-th>
						<uni-th width="170" align="center">创建时间</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.username}}</uni-td>
						<uni-td align="center">{{item.nickname}}</uni-td>
						<uni-td align="center">{{item.role ? item.role.map(item => item).join('、') : '-'}}</uni-td>
						<uni-td align="center">{{item.college ? item.college.map(item=> item.college_name).join('') : '-'}}</uni-td>
						<uni-td align="center">{{item.mobile}}</uni-td>
						<uni-td align="center">{{item.role && item.role.includes('admin') ? '启用' : parseUserStatus(item.status)}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :date="item.
register_date" :threshold="[0, 0]" />
						</uni-td>
						<uni-td align="center">
							<view v-if="item._id === userInfo._id">-</view>
							<view v-else class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id)" class="uni-button" size="mini" type="primary">修改</button>
								<button @click="confirmDelete(item)" class="uni-button" size="mini" type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count"
					 @change="onPageChanged" />
				</view>
			</uni-clientdb>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script>
	const db = uniCloud.database()
	// 表查询配置
	const dbCollectionName = 'uni-id-users,uni-id-roles,hr-college'
	const dbOrderBy = 'username' // 排序字段
	const dbSearchFields = ['username','nickname'] // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 10
	const pageCurrent = 1

	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				query: '',
				where: '',
				role:'',
				selectValue: '',
				orderby: dbOrderBy,
				collectionName: dbCollectionName,
				roleOptions:[{
          value: 'STUDENT',
          label: '学生'
        },{
          value: 'TEACHER',
          label: '教师'
        },{
          value: 'ADMIN',
          label: '管理员'
        }],
				options: {
					pageSize,
					pageCurrent
				},
				selectOptions:[{value:'STUDENT',label:'学生'},{value:'TEACHER',label:'教师'},{value:'',label:'全部'},]
			}
		},
		computed: {
			...mapState('user', ['userInfo']),
		},
		methods: {
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				console.log(newWhere)
				console.log(this.role)
				if(this.selectValue === ''){
					console.log(111)
					this.where =  newWhere
				}else if( this.selectValue !== '' && newWhere === ""){
					console.log(222)
					this.where = this.role
				}else {
					console.log(333)
					this.where = this.role +"&&"+ newWhere
				}
				// const isSameWhere = newWhere === this.where
				// if (isSameWhere) { // 相同条件时，手动强制刷新
				// 	this.loadData()
				// }
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			// 模板下载
			tempFile(){
				uni.showLoading({
					title: '下载中...',
					mask: true
				})
				uni.downloadFile({
				    url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-b8429b16-282a-4d89-b062-ab9c4c2779d1/62675596-41a6-4973-bd16-0b6976de67f1.xlsx', 
				    success: (res) => {
							var filePath = res.tempFilePath;
							if (res.statusCode === 200) {
									uni.showToast({
										title: '下载成功'
									})
									uni.openDocument({
										filePath: filePath,
										success: function (res) {}
									});
							}
							
				    }
				});
				uni.hideLoading()
			},
			// 上传文件
			uploadFile(){
				uni.chooseFile({
				  count: 1, //默认100
				  extension:['.xlsx','.xls'],
				    success: async (res)=>{
							uni.showLoading({
								title: '导入中...',
								mask: true
							})
							console.log(res)
				      if (res.tempFilePaths.length > 0) {
								let filePath = res.tempFilePaths[0]
								// 将文件存入服务器
								uni.uploadFile({
									url: 'http://localhost:3000/uploadfile', 
									filePath: filePath,
									name: 'file',
									success: (res) => {
										let filePath = JSON.parse(res.data).filePath
										// 取出excel数据
										uni.request({
										    url: 'http://localhost:3000/filedata',
												method:'POST',
										    data: {
										        filePath: filePath
										    },
										    success: (res) => {
										        console.log(res.data.data);
												if(res.data.data.length < 3){
													uni.showModal({
														content: '服务异常，请重试',
														showCancel: false
													})
													uni.hideLoading()
													return
												}
														// 使用 uni-clientDB 提交数据
														this.$request('user/batchImport', res.data)
														.then((res) => {
															uni.showToast({
																title: "导入成功"
															})
															let student = res.data[0]
															let teacher = res.data[1]
															uni.showModal({
																showCancel:false,
															    title: '提示',
															    content: `学生表成功有：${student.succCount},失败有：${student.failCount}\n教师表成功有：${teacher.succCount},失败有：${teacher.failCount} `,
															    success: function (res) {
																		setTimeout(() => uni.navigateTo({
																			url: '/pages/system/user/list'
																		}), 1000)
																	}
															});
														}).catch((err) => {
															uni.showModal({
																content: err.message || '请求服务失败',
																showCancel: false
															})
														}).finally(() => {
															uni.hideLoading()
														})
										    }
										});
									}
								})
							}
				    }
				});
			},
			navigateTo(url) {
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData()
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			//批量删除
			delTable() {
				const ids = this.selectedItems()
				const currentUserId = this.userInfo._id
				if (ids.includes(currentUserId)) {
					uni.showToast({
						icon: 'none',
						title: '当前账号不能删除自己',
						duration: 1500
					})
					return
				}
				this.$refs.udb.remove(ids)
			},
			// 修改下拉时
			selectChange(e){
				console.log(e,this.selectValue)
				this.role = `role in ['${e}']`
				this.search()
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(item) {
				const currentUserId = this.userInfo._id
				if (currentUserId === item._id) {
					uni.showToast({
						icon: 'none',
						title: '不允许账号删除自己',
						duration: 1500
					})
					return
				}
				this.$refs.udb.remove(item._id)
			},
			parseUserStatus(status) {
				if (status === 0) {
					return '启用'
				} else if (status === 1) {
					return '禁用'
				} else if (status === 2) {
					return '审核中'
				} else if (status === 3) {
					return '审核拒绝'
				} else {
					return '未知'
				}
			}
		}
	}
</script>
<style>
	/* #ifndef H5 */
	page {
		padding-top: 85px;
	}
	/* #endif */
	
	.upload{
		margin-right: 20rpx;
	}
	.select{
		/* margin-right: 600rpx; */
		justify-items: left;
	}
</style>
